package com.ali.resource.ServicePage;

import com.ali.resource.CompoentPage.RdsComponent;
import com.ali.resource.MapPage.rds.RdsMap;
import com.ali.resource.ShareTools.BasicTools;
import com.ali.resource.ShareTools.TeaopenapiClient;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.rds20140815.models.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class RdsService {
    @Autowired
    private RdsComponent rdsComponent;

    @Autowired
    private TeaopenapiClient teaopenapiClient;



    public void getXlsx(ArrayList<RdsMap> rdsList) throws IOException {
        XSSFWorkbook sheets = new XSSFWorkbook();
        XSSFSheet sheet = sheets.createSheet();
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("DBInstanceId");
        row.createCell(1).setCellValue("DBInstanceName");
        row.createCell(2).setCellValue("EngineVersion");
        row.createCell(3).setCellValue("cpuInfo");
        row.createCell(4).setCellValue("memInfo");
        row.createCell(5).setCellValue("storage");
        row.createCell(6).setCellValue("storageType");
        row.createCell(7).setCellValue("DBInstanceType");
        row.createCell(8).setCellValue("Category");
        row.createCell(9).setCellValue("ReadOnlyDBInstanceIds");
        row.createCell(10).setCellValue("lll:deployment:environment");
        row.createCell(11).setCellValue("lll:business:application-name");
        row.createCell(12).setCellValue("lll:business:application-owner");
        row.createCell(13).setCellValue("lll:business:tech-owner");
        row.createCell(14).setCellValue("lll:business:vendor");
        row.createCell(15).setCellValue("VpcId");
        row.createCell(16).setCellValue("VSwitchId");

        int number = 1;
        for (RdsMap rdsMap : rdsList) {
            XSSFRow row1 = sheet.createRow(number);
            row1.createCell(0).setCellValue(rdsMap.getDBInstanceId());
            row1.createCell(1).setCellValue(rdsMap.getDBInstanceName());
            row1.createCell(2).setCellValue(rdsMap.getEngineVersion());
            row1.createCell(3).setCellValue(rdsMap.getCpuInfo());
            row1.createCell(4).setCellValue(rdsMap.getMemInfo());
            row1.createCell(5).setCellValue(rdsMap.getDbInstanceStorage());
            row1.createCell(6).setCellValue(rdsMap.getDbInstanceStorageType());
            row1.createCell(7).setCellValue(rdsMap.getDbInstanceType());
            row1.createCell(8).setCellValue(rdsMap.getCategory());
            row1.createCell(9).setCellValue(rdsMap.getReadOnlyDBInstanceIds());
            row1.createCell(10).setCellValue(rdsMap.getEnvironment());
            row1.createCell(11).setCellValue(rdsMap.getApplicationName());
            row1.createCell(12).setCellValue(rdsMap.getApplicationOwner());
            row1.createCell(13).setCellValue(rdsMap.getTechOwner());
            row1.createCell(14).setCellValue(rdsMap.getVendor());
            row1.createCell(15).setCellValue(rdsMap.getVpcId());
            row1.createCell(16).setCellValue(rdsMap.getVSwitchId());

            number += 1;
        }

        File file = BasicTools.setFIlePath("rds.xlsx");

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        sheets.write(fileOutputStream);
        fileOutputStream.close();
        sheets.close();
    }

    public ArrayList<RdsMap> getRdsList(@RequestParam(required = true,defaultValue = "false") String bool
            , @RequestParam(required = false) String instanceIdPrefix
            , @RequestParam(required = false) String instanceNamePrefix) throws Exception {

        DescribeDBInstancesResponse dirClient = rdsComponent.getInstanceResource(rdsComponent.getRdsReQuest());
        int totalRecordCount = dirClient.getBody().getTotalRecordCount();

        int page = (totalRecordCount / 50);
        if (0 != (totalRecordCount % 50)) {
            page += 1;
        }

        ArrayList<RdsMap> rdsList = new ArrayList<>();
        for (int i = 1; i < page + 1; i++) {
            DescribeDBInstancesRequest rdsReQuest = rdsComponent.getRdsReQuest();
            rdsReQuest.setPageSize(50);
            rdsReQuest.setPageNumber(i);
            DescribeDBInstancesResponse response = rdsComponent.getInstanceResource(rdsReQuest);

            List<DescribeDBInstancesResponseBody.DescribeDBInstancesResponseBodyItemsDBInstance> dbInstance = response.getBody().getItems().getDBInstance();

            for (DescribeDBInstancesResponseBody.DescribeDBInstancesResponseBodyItemsDBInstance instance : dbInstance) {

                RdsMap rdsMap = this.getRdsMap(instance);

                if (instanceIdPrefix != null && instanceNamePrefix != null){

                    if (instance.getDBInstanceId().toLowerCase().contains(instanceIdPrefix.toLowerCase().trim()) && instance.getDBInstanceDescription().toLowerCase().contains(instanceNamePrefix.toLowerCase().trim())){
                        rdsList.add(rdsMap);
                    }

                } else if (instanceIdPrefix != null && instanceNamePrefix == null){

                    if (instance.getDBInstanceId().toLowerCase().contains(instanceIdPrefix.toLowerCase().trim())){
                        rdsList.add(rdsMap);
                    }

                } else if (instanceNamePrefix != null && instanceIdPrefix == null){

                    if (instance.getDBInstanceDescription().toLowerCase().contains(instanceNamePrefix.toLowerCase().trim())){
                        rdsList.add(rdsMap);
                    }

                } else if (instanceIdPrefix == null && instanceNamePrefix == null){
                    rdsList.add(rdsMap);
                }
            }
        }
        return rdsList;
    }

    public RdsMap getRdsMap(DescribeDBInstancesResponseBody.DescribeDBInstancesResponseBodyItemsDBInstance instance) throws Exception {

        DescribeDBInstanceAttributeResponse instanceInfo = rdsComponent.getInstanceInfo(instance.getDBInstanceId());
        DescribeDBInstanceAttributeResponseBody.DescribeDBInstanceAttributeResponseBodyItemsDBInstanceAttribute dbAttr = instanceInfo.getBody().getItems().getDBInstanceAttribute().get(0);

        RdsMap rdsMap = new RdsMap();

        String[] strings = new String[dbAttr.getReadOnlyDBInstanceIds().getReadOnlyDBInstanceId().size()];
        if (dbAttr.getReadOnlyDBInstanceIds().getReadOnlyDBInstanceId().size() > 0){
            for (int i = 0; i < dbAttr.getReadOnlyDBInstanceIds().getReadOnlyDBInstanceId().size(); i++) {
                strings[i] = dbAttr.getReadOnlyDBInstanceIds().getReadOnlyDBInstanceId().get(i).getDBInstanceId();
            }
            rdsMap.setReadOnlyDBInstanceIds(String.join(",",strings));

        }

        rdsMap.setDBInstanceId(dbAttr.getDBInstanceId());
        rdsMap.setDBInstanceName(dbAttr.getDBInstanceDescription());
        rdsMap.setEngineVersion(dbAttr.getEngine() + ":" + dbAttr.getEngineVersion());
        rdsMap.setCpuInfo(dbAttr.getDBInstanceCPU().toString());
        rdsMap.setMemInfo(dbAttr.getDBInstanceMemory().toString());
        rdsMap.setDbInstanceStorage(dbAttr.getDBInstanceStorage().toString());
        rdsMap.setDbInstanceStorageType(dbAttr.getDBInstanceStorageType());
        rdsMap.setDbInstanceType(dbAttr.getDBInstanceType());
        rdsMap.setCategory(dbAttr.getCategory());
        rdsMap.setVpcId(dbAttr.getVpcId());
        rdsMap.setVSwitchId(dbAttr.getVSwitchId());

        DescribeDBInstanceByTagsResponse instanceByTagsInfo = rdsComponent.getInstanceByTagsInfo(instance.getDBInstanceId());
        List<DescribeDBInstanceByTagsResponseBody.DescribeDBInstanceByTagsResponseBodyItemsDBInstanceTag> dbInstanceTag = instanceByTagsInfo.getBody().getItems().getDBInstanceTag();
        for (int n = 0; n < dbInstanceTag.size(); n++) {
            DescribeDBInstanceByTagsResponseBody.DescribeDBInstanceByTagsResponseBodyItemsDBInstanceTagTags tags = dbInstanceTag.get(n).getTags();
            if (tags != null) {
                for (int i2 = 0; i2 < tags.getTag().size(); i2++) {
                    if (tags.getTag().get(i2).getTagKey().equals("lll:deployment:environment")) {
                        rdsMap.setEnvironment(tags.getTag().get(i2).getTagValue());
                    } else if (tags.getTag().get(i2).getTagKey().equals("lll:business:application-name")) {
                        rdsMap.setApplicationName(tags.getTag().get(i2).getTagValue());
                    } else if (tags.getTag().get(i2).getTagKey().equals("lll:business:application-owner")) {
                        rdsMap.setApplicationOwner(tags.getTag().get(i2).getTagValue());
                    } else if (tags.getTag().get(i2).getTagKey().equals("lll:business:tech-owner")) {
                        rdsMap.setTechOwner(tags.getTag().get(i2).getTagValue());
                    } else if (tags.getTag().get(i2).getTagKey().equals("lll:business:vendor")) {
                        rdsMap.setVendor(tags.getTag().get(i2).getTagValue());
                    }
                }
            }
        }

        return rdsMap;
    }

}
